package cn.twh.wall.beetl.function;

import java.util.LinkedHashMap;

/**
 * 缓存函数 最大缓存数为1000，暂不考虑配置化
 *
 * @author TWH
 */
public class Cache {

    private static final LinkedHashMap<String, Object> SEQ_DATA_CACHE = new LinkedHashMap<>();
    private static final LinkedHashMap<String, Object> DATA_CACHE = new LinkedHashMap<>();
    private static final int MAX_CACHE = 1000;

    public static void clearSeqCache() {
        SEQ_DATA_CACHE.clear();
    }

    public static void addSeqDataCache(String key, Object value) {
        addDataCache(key, value, SEQ_DATA_CACHE);
    }

    public static Object getSeqDataCache(String key, boolean remove) {
        if (remove) {
            return SEQ_DATA_CACHE.remove(key);
        }
        return SEQ_DATA_CACHE.get(key);
    }

    public static void addDataCache(String key, Object value) {
        addDataCache(key, value, DATA_CACHE);
    }

    private static void addDataCache(String key, Object value,
                                     LinkedHashMap<String, Object> dataCache) {
        if (dataCache.size() > MAX_CACHE) {
            // 移除最后一个
            dataCache.remove(dataCache.keySet().toArray()[MAX_CACHE - 1]);
        }
        dataCache.put(key, value);
    }

    public static Object getDataCache(String key) {
        return DATA_CACHE.get(key);
    }
}
